package com.kugou.internal;

import java.io.*;

/**
 * Created by Alex on 2014/10/17
 */
public class MiscUtils {
    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static String getStackTrace(final Throwable throwable) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        return sw.getBuffer().toString();
    }

    public static void writeStringToFile(File file, String content, String encoding)
            throws IOException {
        byte[] bytes = content.getBytes(encoding);
        writeByteArrayToFile(file, bytes);
    }

    public static void writeByteArrayToFile(File file, byte[] bytes)
            throws IOException {
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        try (OutputStream out = new FileOutputStream(file)) {
            out.write(bytes);
            out.flush();
        }
    }
    public static String readFileToString(File file) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line = reader.readLine();
            while (line != null) {
                sb.append(line);
                line = reader.readLine();
            }
        }
        return sb.toString();
    }
    public static byte[] toByteArray(InputStream in) throws IOException {
        try(ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            int nRead;
            byte[] data = new byte[in.available()];
            while ((nRead = in.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            return buffer.toByteArray();
        } finally {
            in.close();
        }
    }
}

